#include <etcd/Client.hpp>
#include <etcd/KeepAlive.hpp>
#include <etcd/Response.hpp>
#include <etcd/Watcher.hpp>
#include <etcd/Value.hpp>
#include <thread>
#include <iostream>

void callback(const etcd::Response &response)
{
    if (response.is_ok() == false)
    {
        std::cout << "收到错误事件，原因[" << response.error_message() << "]" << std::endl;
        return;
    }

    // .events() 返回存储事件的vector
    for (auto event : response.events())
    {
        // 获取事件类型
        auto type = event.event_type();

        if (type == etcd::Event::EventType::PUT)
        {
            std::cout << "服务内容发生改变！！！" << std::endl;
            std::cout << "current service: [" << event.kv().key() << "-" << event.kv().as_string() << "]" << std::endl;
            std::cout << "prev service: [" << event.prev_kv().key() << "-" << event.prev_kv().as_string() << "]" << std::endl;
        }
        else if (type == etcd::Event::EventType::DELETE_)
        {
            std::cout << "服务下线" << std::endl;
            std::cout << "current service: [" << event.kv().key() << "-" << event.kv().as_string() << "]" << std::endl;
            std::cout << "prev service: [" << event.prev_kv().key() << "-" << event.prev_kv().as_string() << "]" << std::endl;
        }
    }
}

int main(int argc, char *argv[])
{
    std::string etcd_host = "http://127.0.0.1:2379";
    // 实例化一个etcd客户端
    etcd::Client client(etcd_host);
    // 获取指定键值对对象   --监控service目录下的键值对
    auto response = client.ls("/service").get();
    if (response.is_ok() == false)
    {
        std::cout << "新增数据失败，原因[" << response.error_message() << "]" << std::endl;
        return -1;
    }
    int size = response.keys().size();
    for (int i = 0; i < size; i++)
    {
        std::cout << response.value(i).as_string() << "提供服务[" << response.key(i) << "]" << std::endl;
    }
    auto watcher = etcd::Watcher(client, "/service", callback, true);
    watcher.Wait();
}